package com.zrrd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.model.product.SpuImage;
import com.zrrd.model.product.SpuInfo;
import com.zrrd.model.product.SpuSaleAttr;
import com.zrrd.model.product.SpuSaleAttrValue;
import com.zrrd.product.mapper.SpuImageMapper;
import com.zrrd.product.mapper.SpuInfoMapper;
import com.zrrd.product.mapper.SpuSaleAttrMapper;
import com.zrrd.product.mapper.SpuSaleAttrValueMapper;
import com.zrrd.product.service.SpuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Override
    @Transactional
    public void saveSpu(SpuInfo spuInfo) {
        this.save(spuInfo);
        //2.保存图片到spu_image表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        for (SpuImage spuImage : spuImageList) {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);

        }
        //3.保存spu的销售属性以及属性值到
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            //设置关联的spu
            spuSaleAttr.setSpuId(spuInfo.getId());
            //执行添加属性
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4.
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                //设置关联的spu
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //设置所关联的属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                //执行添加属性值
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);

            }
        }

    }

    @Override
    public List<SpuImage> getSpuImage(Long spuId) {
        QueryWrapper<SpuImage> wrapper=new QueryWrapper<>();
        wrapper.eq("spu_id",spuId);
        return spuImageMapper.selectList(wrapper);
    }

    @Override
    public List<SpuSaleAttr> SpuSaleAttrList(Long spuId) {
      return  spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }
}
